package data5u

import (
	"github.com/PuerkitoBio/goquery"
	"github.com/ruoklive/proxypool/internal/ipgetter/base"
	"github.com/ruoklive/proxypool/pkg/models"
	"github.com/ruoklive/proxypool/pkg/register"
	"go.uber.org/zap"
	"io"
	"strconv"
)

func init() {
	register.Add(func() register.IPGetter {
		return New()
	})
}

type IPGetter struct {
	base.Base
}

func New() *IPGetter {
	g := &IPGetter{}
	g.Base = base.NewBase("http://www.data5u.com/free/index.shtml",g.Parse,"Data5u")
	return g
}

func (g *IPGetter) Parse(body io.ReadCloser) (result []*models.IP) {
	doc, err := goquery.NewDocumentFromReader(body)
	if err != nil {
		g.Error("Parse fail!",zap.Error(err))
		return
	}

	doc.Find("body > div.wlist > ul > li:nth-child(2) > ul").Each(func(i int, s *goquery.Selection) {
		node := strconv.Itoa(i + 1)
		ss := s.Find("ul:nth-child(" + node + ") > span:nth-child(1) > li").Text()
		sss := s.Find("ul:nth-child(" + node + ") > span:nth-child(2) > li").Text()
		ssss := s.Find("ul:nth-child(" + node + ") > span:nth-child(4) > li").Text()
		ip := models.NewIP()
		ip.Data = ss + ":" + sss
		ip.Type1 = ssss
		g.Info("GET IP",zap.String("ip",ip.String()))
		result = append(result, ip)
	})
	g.Info("done.")
	return
}
